package com.han.hotelplat.controller.task;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.han.hotelplat.comm.Constant;
import com.han.hotelplat.comm.ResponseWrapTo;
import com.han.hotelplat.comm.ResponseWrapTo.CodeType;
import com.han.hotelplat.comm.base.Pager;
import com.han.hotelplat.comm.utils.AreaHelp;
import com.han.hotelplat.comm.utils.DateUtil;
import com.han.hotelplat.comm.utils.ListSortUtil;
import com.han.hotelplat.comm.utils.LocationUtils;
import com.han.hotelplat.comm.utils.LogUtil;
import com.han.hotelplat.comm.utils.NumberUtil;
import com.han.hotelplat.comm.utils.RequestUtil;
import com.han.hotelplat.comm.utils.StrUtil;
import com.han.hotelplat.manager.LogManager;
import com.han.hotelplat.model.AreaModel;
import com.han.hotelplat.model.TaskLogModel;
import com.han.hotelplat.pojo.childtask.Childtask;
import com.han.hotelplat.pojo.employee.Employee;
import com.han.hotelplat.pojo.emscheduling.Emscheduling;
import com.han.hotelplat.pojo.emtask.Emtask;
import com.han.hotelplat.pojo.hotel.Hotel;
import com.han.hotelplat.pojo.hotelmanager.Hotelmanager;
import com.han.hotelplat.pojo.log.Logger;
import com.han.hotelplat.pojo.systemuser.Systemuser;
import com.han.hotelplat.pojo.task.Task;
import com.han.hotelplat.seo.SEO;
import com.han.hotelplat.service.childtask.ChildTaskService;
import com.han.hotelplat.service.emscheduling.EmschedulingService;
import com.han.hotelplat.service.emtask.EmTaskService;
import com.han.hotelplat.service.hotel.HotelService;
import com.han.hotelplat.service.hotelmanager.HotelmanagerService;
import com.han.hotelplat.service.systemuser.SystemuserService;
import com.han.hotelplat.service.task.TaskService;

@Controller
@RequestMapping("/task/*")
public class TaskController {
	
	@Autowired
	private TaskService taskService;
	@Autowired
	private HotelService hotelService;
	@Autowired
	private EmTaskService emTaskService;
	@Autowired
	private ChildTaskService childTaskService;
	@Autowired
	private HotelmanagerService hotelmanagerService;
	@Autowired
	private LogManager logManager;
	@Autowired
	private SystemuserService systemuserService;
	@Autowired
	private EmschedulingService emschedulingService;
	
	/**
	 * form表单提交 Date类型数据绑定 <功能详细描述>
	 * 
	 * @param binder
	 * @see [类、类#方法、类#成员]
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		
		//实现表单中的字符串自动转换为Date或者Timestamp 类型。
		//http://www.micmiu.com/j2ee/spring/springmvc-binding-date/
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// ("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		//binder.registerCustomEditor(java.sql.Timestamp.class, new CustomTimestampEditor(dateFormat, true));
	}
	
	/**
	 * 
		 * @description	帮工获取自己的任务详情
		 * @author  han1088
		 * @param userid
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "submitTaskRemark", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String submitTaskRemark(String taskid, Integer userType,String remark){
		String userid = "";
		String realname = "";
		String host = RequestUtil.getRequest().getRemoteHost();
		if(userType.equals(Constant.USER_TYPE_EMPLOYEE)){
			Employee empu = (Employee) RequestUtil.getSession().getAttribute(Constant.SESSION_LOGIN_USER);
			if(empu == null){
				return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
			}
			userid = empu.getUserid();//帮工的钱包用户ID储存的是帮工的用户ID
			realname = empu.getRealname();
		}
		if(userType.equals(Constant.USER_TYPE_HOTELMANAGER)){
			Hotelmanager systemu = (Hotelmanager) RequestUtil.getSession().getAttribute(Constant.SESSION_LOGIN_USER);
			if(systemu == null){
				return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
			}
			userid = systemu.getHotelid().toString();//酒店的钱包用户ID存储的是酒店ID
			realname = systemu.getRealname();
		}
		if(userType.equals(Constant.USER_TYPE_PLATFORM)){
			Systemuser systemu = (Systemuser) RequestUtil.getSession().getAttribute(Constant.CMS_SESSION_LOGIN_USER);
			if(systemu == null){
				return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
			}
			 userid = systemu.getUserid();
			 realname = systemu.getRealname();
		}

		Task t = taskService.getHotelTaskDteail(taskid);
		if(t==null){
			return new ResponseWrapTo(CodeType.fail, "任务不存在", null).toJson();
		}
		Logger logger = new Logger(new Date(), userid, host,realname);
		String context = remark;
		TaskLogModel tlm = new TaskLogModel();
		tlm.setContext(context);
		tlm.setOptcode(Constant.logger.LOG_TASK_SUBMITREMARK);
		tlm.setTaskid(taskid);
		logManager.creatTaskLog(tlm, logger);
		return new ResponseWrapTo(CodeType.success, "备注提交成功", null).toJson();
	}
	
	/**
	 * 
		 * @description	帮工获取自己的任务详情
		 * @author  han1088
		 * @param userid
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getEmployeeTaskDetail", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getEmployeeTaskDetail(String taskid){
		Employee employee = null;
		try{
			employee = (Employee) RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER);
		}catch(Exception e){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		if(employee == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		Task task = taskService.getEmployeeTaskDteail(taskid,employee.getUserid());
		if(task == null){
			return new ResponseWrapTo(-1, "任务不存在", null).toJson();
		}
		if(task.getState().intValue() == Constant.TASK_STATE_CREAT.intValue()
				||task.getState().intValue() == Constant.TASK_STATE_WAITSERVICE.intValue()){
			if(task.getIsJoin().intValue() == 1){
				task.setState(Constant.TASK_STATE_WAITSERVICE);
			}
			
		}
		task.setNowdatetime(new Date());
		Hotel hotel = hotelService.getHotelById(task.getHotelid());
		String tel = "";
		String realname = "";
		if(StringUtils.isNotBlank(task.getTel())){
			tel=task.getTel();
			realname = task.getRealname();
		}else{
			Hotelmanager hm = hotelmanagerService.findByUserid(task.getPublisher());
			if(hm == null){//可能是后台人员发布的订单
				Systemuser user = systemuserService.findUserByUserid(task.getPublisher());
				if(user != null){
					tel=user.getTel();
					realname = user.getRealname();
				}else{
					System.out.println(task.getPublisher());
				}
			}else{
				tel=hm.getTel();
				realname = hm.getRealname();
			}
		}
		task.setRealname(realname);
		task.setTel(tel);
		if(hotel.getArea() != null){
			hotel.setAreaModel(AreaHelp.getInstance().getAreaModels(hotel.getArea().toString()));
		}
		if(StringUtils.isBlank(task.getWelfare())){
			task.setWelfare(hotel.getWelfare()==null?"[]":hotel.getWelfare());
		}
		JSONObject js = JSONObject.parseObject(JSONObject.toJSONString(task,SerializerFeature.DisableCircularReferenceDetect,
				SerializerFeature.WriteDateUseDateFormat,SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteNullStringAsEmpty));
		js.put("hotel", hotel);
		if(task.getDays()<=0){
			js.put("averroomcount", 0);//已清洁总量
		}else{
			js.put("averroomcount", task.getSumroomcount()/task.getDays());
		}
		return new ResponseWrapTo(CodeType.success, "", js).toJson();
	}
	
	
	
	/**
	 *帮工接单，获取酒店发布的任务列表
		 * @description	
		 * @author  han1088
		 * @param lat 纬度
		 * @param lon 经度
		 * @param startdate 日期开始
		 * @param enddate 日期结束
		 * @param distance 距离
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "findEmpolyeeTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String findEmpolyeeTask(String lat, String lon, String city,
			String startdate, String enddate, Integer distance,Integer pageNo){
		LogUtil.info("帮工搜索任务，lat="+lat+";lon="+lon+";city"+city+";startdate="+startdate+";enddate="+enddate+";distance"+distance);
		Employee employee = null;
		try{
			employee = (Employee) RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER);
			/*if(employee == null){
				return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
			}*/
		}catch(Exception e){
			//测试阶段先写死
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		int level = 4;//用户未登录直接写死4级的清洁等级
		if(employee != null){
			if(employee.getState().intValue() == Constant.USER_STATE_NO_PASS){
				level = 1;//审核不通过的只能看到1级的
			}else{
				level = employee.getLevel();//帮工等级
			}
		}
		List<Task> taskli = new ArrayList<Task>();
		List<Task> tli = new ArrayList<Task>();
		if(StrUtil.isNullOrEmpty(city)){
			city = "440100";
		}
		Date startTime = null;
		Date endTime = null;
		if(StringUtils.isNotBlank(startdate)){
			startTime = DateUtil.parseYMD(startdate);
		}
		if(StringUtils.isNotBlank(enddate)){
			endTime = DateUtil.parseYMDHMS(enddate+" 23:59:59");
		}
		if(pageNo == null){
			tli = taskService.getHotelTask(null, Constant.TASK_STATE_CREAT, startTime, endTime);
		}else{
			Pager<Task> page = taskService.getHotelTaskByPage(null, startTime, endTime, pageNo, Integer.parseInt(city));
			//查询所有发布中的任务
			tli = page.getList();
			if(tli.size() == 0 && pageNo.intValue()<page.getTotalPage()){
				pageNo += pageNo;
			}
		}
		for(Task t : tli){
			Hotel h = hotelService.getHotelById(t.getHotelid());
			Emtask emTask = emTaskService.getEmTask(t.getTaskid(), employee.getUserid());
			if(h == null || h.getArea() == null){
				continue;
			}
			AreaModel [] areaModer= AreaHelp.getInstance().getAreaModels(h.getArea().toString());
			AreaModel a = areaModer[1];//市级
			if(!city.equals(a.getCode())){
				continue;
			}
			
			if(t.getShowapp().intValue() == Constant.APP_SHOW_CLOSE && emTask == null){//未报名的帮工，APP不可见任务
				continue;
			}
			/*if(t.getStarttime().getTime() <= System.currentTimeMillis()){//已经过时了就不返回了
				continue;
			}*/
			if(emTask != null && emTask.getCanceltime() == null){//已经报名了就不用返回了
				t.setIsJoin(1);//已经报名
			}else{
				t.setIsJoin(2);//已经报名
			}
			int count = emTaskService.getEmTaskByTakid(t.getTaskid()).size();//已经接单的帮工人数
			/*if(count >= t.getUsercount().intValue()){//已经报名满了
				continue;
			}*/
			String location = h.getLocation();
			t.setHotel(h);
			t.setLocation(location);
			t.setHotelname(h.getHotelname());
			t.setUnitprice(t.getEmunitprice());//帮工看到帮工的单价
			t.setEmenroll(count);
			double dist = 0;
			DecimalFormat    df   = new DecimalFormat("######0"); 
			try{
				JSONObject locationjs = JSONObject.parseObject(t.getLocation());
				double hotellon = locationjs.getDoubleValue("lon");//酒店经度
				double hotellat = locationjs.getDoubleValue("lat");//酒店纬度
				double locallon = Double.parseDouble(lon);//当前位置经度
				double locallat = Double.parseDouble(lat);//当前位置纬度
				dist = LocationUtils.getDistance(hotellat, hotellon, locallat, locallon)/1000;//公里为单位
			}catch(Exception e){
				
			}
			if(dist<1){
				dist = 1.0;
			}
			t.setDistance(df.format(dist)+"");
			boolean filter = true;
			if(!startdate.isEmpty()){
				if(DateUtil.daysDistance(t.getStarttime(), DateUtil.parseYMD(startdate))>0){
					filter = false;
				}
			}
			if(!enddate.isEmpty()){
				if(DateUtil.daysDistance(t.getStarttime(), DateUtil.parseYMD(enddate))<0){
					filter = false;
				}
			}
			
			if(distance != null){//选择了距离过滤
				if("".equals(distance)){
					filter = true;
				}else{
					
					if(dist>distance.doubleValue()){
						filter = false;
					}
				}
			}
			if(filter && level>=h.getLevel()){
				taskli.add(t);
			}
			
		}
		ListSortUtil<Task> sortList = new ListSortUtil<Task>();
		sortList.sort(taskli, "starttime", true);
		for(Task t : taskli){
			int weightDistance = 0;
			if(!lon.isEmpty()&& !lon.isEmpty()){
				JSONObject locationjs = JSONObject.parseObject(t.getLocation());
				double hotellon = locationjs.getDoubleValue("lon");//酒店经度
				double hotellat = locationjs.getDoubleValue("lat");//酒店纬度
				double locallon = Double.parseDouble(lon);//当前位置经度
				double locallat = Double.parseDouble(lat);//当前位置纬度
				LogUtil.info("当前经度："+lon+",纬度："+lat);
				String [] dest = new String[]{hotellat+"",hotellon+""};
				String [] current = new String[]{locallat+"",locallon+""};
				System.out.println("====================");
				weightDistance = SEO.getDistanceWeight(current, dest);//按距离算权重
				System.out.println("距离权重:"+weightDistance);
			}
			
			int weightDate = SEO.getDateWeight(new Date(),t.getStarttime());//按时间算权重
			System.out.println("日期权重:"+weightDate);
			int weight = weightDistance + weightDate;
			System.out.println("总权重:"+weight);
			System.out.println(t.getHotelname());
			System.out.println("====================");
			t.setWeight(weight);
		}
		Collections.sort(taskli,new Comparator<Task>() {
	            @Override
	            public int compare(Task o1, Task o2) {
	                // TODO Auto-generated method stub
	                return o2.getWeight()-o1.getWeight();
	            }
	     });
		Collections.sort(taskli,new Comparator<Task>() {
            @Override
            public int compare(Task o1, Task o2) {
                // TODO Auto-generated method stub
                return o1.getState()-o2.getState();
            }
		});
		//page.setList(taskli);
		return new ResponseWrapTo(0, "数据获取成功", taskli).toJson();
	}
	
	/**
	 * 
		 * @description	帮工提交考勤
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "submitTaskAttendance", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String submitTaskAttendance(String taskid,String date, Float roomcount, String roomDetail){
		Employee employee = (Employee) RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER);
		if(employee == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登陆",null).toJson();
		}
		if(StringUtils.isBlank(date)){
			date = DateUtil.formatYMD(new Date());
		}
		Map<String, Object> data = childTaskService.submitTaskAttendance(taskid, 
				date, employee.getUserid(),roomcount,roomDetail);
		
		Integer code = (Integer) data.get("code");
		String message = (String) data.get("message");
		return new ResponseWrapTo(code, message,null).toJson();
	}
	
	
	/**
	 * 
		 * @description	帮工取消任务
		 * @author  han1088
		 * @param emid
		 * @param taskid
		 * @param remark
		 * @param constraint
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "cancerEmTaskByEm", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String cancerEmTaskByEm(String taskid, String cancercause){
		Employee employee = (Employee) RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER);
		if(employee == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		Map<String, Object> reMap = taskService.cancerEmTaskByEm(employee.getUserid(),taskid,cancercause);
		int code = (int) reMap.get("code");
		if(code == 0){
			String host = RequestUtil.getRequest().getRemoteHost();
			Logger logger = new Logger(new Date(), employee.getUserid(), host,employee.getRealname());
			String context = "帮工取消任务";
			TaskLogModel tlm = new TaskLogModel();
			tlm.setContext(context);
			tlm.setOptcode(Constant.logger.LOG_TASK_CANCE);
			tlm.setTaskid(taskid);
			logManager.creatTaskLog(tlm, logger);
		}
		String message =  reMap.get("message").toString();
		return new ResponseWrapTo(code, message, null).toJson();
	}
	
	/**
	 * 
		 * @description	酒店取消任务
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "cancerTaskByHotel", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String cancerTaskByHotel(String taskid, String cancercause){
		Hotelmanager hm = RequestUtil.getSessionAttributeOnce(Constant.SESSION_LOGIN_USER,Hotelmanager.class);
		if(hm == null){
			return new ResponseWrapTo(ResponseWrapTo.CodeType.forbidden, "用户未登录", null).toJson();
		}
		Map<String, Object> reMap = taskService.cancerTaskByHotel(taskid,cancercause,"2="+hm.getUserid());
		int code = (int) reMap.get("code");
		if(code == 0){
			if(code == 0){//取消成功
				String host = RequestUtil.getRequest().getRemoteHost();
				Logger logger = new Logger(new Date(), hm.getUserid(), host,hm.getRealname());
				String context = "管家取消任务";
				TaskLogModel tlm = new TaskLogModel();
				tlm.setContext(context);
				tlm.setOptcode(Constant.logger.LOG_TASK_CANCE);
				tlm.setTaskid(taskid);
				logManager.creatTaskLog(tlm, logger);
			}
		}
		String message =  reMap.get("message").toString();
		return new ResponseWrapTo(code, message, null).toJson();
	}
	
	/**
	 * 
		 * @description	发布任务
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "publicTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String publicTask(Task task){
		Hotelmanager hm = RequestUtil.getSessionAttributeOnce(Constant.SESSION_LOGIN_USER,Hotelmanager.class);
		if(hm == null){
			return new ResponseWrapTo(ResponseWrapTo.CodeType.forbidden, "用户未登录", null).toJson();
		}
		String host = RequestUtil.getRequest().getRemoteHost();
		Hotel h = hotelService.getHotelById(hm.getHotelid());
		if(h.getState().intValue() != Constant.HOTEL_STATE_PASS.intValue()){
			return new ResponseWrapTo(-4, "酒店还未通过审核或者已经下架", null).toJson();
		}
		
		if(hm.getHotelid() == null){//还未绑定酒店
			return new ResponseWrapTo(-4, "您的账号还未绑定酒店。", null).toJson();
		}
		
		task.setHotelid(hm.getHotelid());//酒店ID
		task.setPublisher(hm.getUserid());//发布人
		
		String remark = task.getRemark();
		if(remark != null){
			task.setRemark(StrUtil.getSubString(remark,280));
		}
		
		if(DateUtil.daysDistance(new Date(),task.getStarttime()) <= 0){
			return new ResponseWrapTo(-3, "抱歉，距离开始日期太短，没有适合的帮工匹配，请选择其他日期。", null).toJson();
		}
		if(DateUtil.formatYMD(DateUtil.getRelativeDay(new Date(), 1))
				.equals(DateUtil.formatYMD(task.getStarttime()))){
			if(new Date().getHours() >Constant.TASK_TIMEOUT){
				return new ResponseWrapTo(-3, "抱歉，距离开始日期太短，没有适合的帮工匹配，请选择其他日期。", null).toJson();
			}
		}
		
		if(DateUtil.daysDistance(task.getStarttime(),task.getEndtime())>31){
			return new ResponseWrapTo(-4, "抱歉，任务天数不能超过31天", null).toJson();
		}
		
		if(DateUtil.daysDistance(task.getStarttime(),task.getEndtime())<0){
			return new ResponseWrapTo(-4, "任务起始时间必须早于结束时间", null).toJson();
		}
		task.setShowapp(Constant.APP_SHOW_OPEN);//客户端可见
		if(StringUtils.isBlank(task.getWelfare())){//福利
			task.setWelfare(h.getWelfare());
		}
		Map<String, Object> reMap = taskService.publicTask(task, Constant.USER_TYPE_HOTELMANAGER);
		int code = (int) reMap.get("code");
		if(code == 0){//发布成功
			Logger logger = new Logger(new Date(), hm.getUserid(), host,hm.getRealname());
			String context = "发布任务";
			TaskLogModel tlm = new TaskLogModel();
			tlm.setContext(context);
			tlm.setOptcode(Constant.logger.LOG_TASK_PUBLIC);
			tlm.setTaskid(task.getTaskid());
			logManager.creatTaskLog(tlm, logger);
		}
		String message =  reMap.get("message").toString();
		return new ResponseWrapTo(code, message, task.getTaskid()).toJson();
	}
	
	/**
	 * 
		 * @description	帮工获取自己的考勤
		 * @author  han1088
		 * @param userid
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getEmAttendance", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getEmAttendance(String taskid, String date){
		Employee employee = (Employee) RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER);
		if(employee == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		Map<String, Object> re= childTaskService.getEmTaskAttendance(taskid, employee.getUserid(), date);
		return new ResponseWrapTo(CodeType.success,"", re.get("childtaskList")).toJson();
	}
	
	/**
	 * 
		 * @description	
		 * @author  han1088
		 * @param state
		 * @param waittask 是否为待处理订单
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getEmployeeTaskList", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getEmployeeTaskList(Integer state, Integer waittask){
		Employee employee = (Employee) RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER);
		if(employee == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		List<Map<String,Object>> response = new ArrayList<Map<String,Object>>();
		List<Task> data = taskService.getEmTaskList(employee.getUserid(),state, waittask);
		ListSortUtil<Task> sortlist = new ListSortUtil<Task>();
		sortlist.sort(data, "accepttime", false);
		for(Task t : data){
			Map<String, Object> taskmap = new HashMap<String, Object>();
			Map<String, Object> hotelmap = new HashMap<String, Object>();
			Hotel hotel = hotelService.getHotelById(t.getHotelid());
			hotelmap.put("hotelid", hotel.getId());
			hotelmap.put("hotelname", hotel.getHotelname());
			taskmap.put("id", t.getId());
			taskmap.put("taskid", t.getTaskid());
			taskmap.put("todayroomcount", t.getTodayroomcount());//今日清洁数
			taskmap.put("sumroomcount", t.getSumroomcount());//已清洁总量
			taskmap.put("days", t.getDays());//已清洁天数
			taskmap.put("emenroll", t.getEmenroll());//帮工人数
			taskmap.put("isJoin", t.getIsJoin());//是否已报名
			taskmap.put("lowestroom", t.getTaskroomcount());//最低房量
			taskmap.put("usercount", t.getUsercount());//需要的帮工数
			if(t.getStarttime().getTime() > System.currentTimeMillis()){
				taskmap.put("countdown", DateUtil.daysDistance(new Date(), t.getStarttime()));
			}else{
				taskmap.put("countdown", 0);
			}
			if(t.getDays()<=0){
				taskmap.put("averroomcount", 0);//已清洁总量
			}else{
				taskmap.put("averroomcount", t.getSumroomcount()/t.getDays());
			}
			
			taskmap.put("unitprice", t.getEmunitprice());//单价
			taskmap.put("consume", t.getConsume());//累积服务费
			taskmap.put("hotel", hotelmap);
			if(t.getState().intValue() == Constant.TASK_STATE_CREAT.intValue()
					||t.getState().intValue() == Constant.TASK_STATE_WAITSERVICE.intValue()){
				if(t.getIsJoin().intValue() == 1){//帮工已经报名的显示待服务状态
					taskmap.put("state", Constant.TASK_STATE_WAITSERVICE);
				}else{
					taskmap.put("state", t.getState());
				}
			}else{
					taskmap.put("state", t.getState());
			}
			if(t.getAccepttime().getTime() > t.getStarttime().getTime()){//任务开始后才报名的
				taskmap.put("starttime", t.getAccepttime());//帮工端显示从报名时间开始
			}else{
				taskmap.put("starttime", t.getStarttime());
			}
			taskmap.put("endtime", t.getEndtime());
			taskmap.put("isConfirmWork", t.getIsConfirmWork());
			taskmap.put("nowdatetime", new Date());
			taskmap.put("isUpWord", t.getIsUpWord());
			taskmap.put("tasktype", t.getTasktype());//默认临时任务
			if(t.getTasktype() == null || t.getTasktype().intValue() == 0){//临时任务
				taskmap.put("accepttype", t.getAccepttype() == null ? 0 : t.getAccepttype());//默认不间断报名
			}
			response.add(taskmap);
		}
		return new ResponseWrapTo(CodeType.success, "", response).toJson();
	}
	
	/**
	 * 
		 * @description	查询酒店自己的订单
		 * @author  han1088
		 * @param state 状态
		 * @param wait 是否为查询待处理订单
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getMyHotelTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getMyHotelTask(Integer state, Integer wait){
		Hotelmanager  user = RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER, Hotelmanager.class);
		if(user == null){
			return new ResponseWrapTo(ResponseWrapTo.CodeType.forbidden, "用户未登录", null).toJson();
		}
	/*	List<Task> re = taskService.getHotelTask(user.getHotelid(), state);
		ListSortUtil<Task> sortLi = new ListSortUtil<Task>();
		sortLi.sort(re, "creattime", false);
		return new ResponseWrapTo(CodeType.success, "", re).toJson();*/
		if(user.getHotelid() == null){
			user.setHotelid(-1);//未绑定酒店的管家
		}
		List<Task> re = taskService.getHotelTask(user.getHotelid(), state, wait);
		ListSortUtil<Task> sortLi = new ListSortUtil<Task>();
		sortLi.sort(re, "creattime", false);
		return new ResponseWrapTo(CodeType.success, "", re).toJson();
	}
	
	/**
	 * 
		 * @description	获取酒店自己的任务
		 * @author  han1088
		 * @param userid
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getMyHotelTaskDetail", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getMyHotelTaskDetail(String taskid){
		Task task = taskService.getHotelTaskDteail(taskid);
		if(task == null){
			return new ResponseWrapTo(-1, "任务不存在", null).toJson();
		}
		Hotel hotel = hotelService.getHotelById(task.getHotelid());
		task.setNowdatetime(new Date());
		if(hotel.getArea() != null){
			hotel.setAreaModel(AreaHelp.getInstance().getAreaModels(hotel.getArea().toString()));
		}
		JSONObject js = JSONObject.parseObject(JSONObject.toJSONString(task,SerializerFeature.DisableCircularReferenceDetect,
				SerializerFeature.WriteDateUseDateFormat,SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteNullStringAsEmpty));
		js.put("hotel", hotel);
		return new ResponseWrapTo(CodeType.success, "", js).toJson();
	}
	
	/**
	 * 查看该任务接单的帮工
	 */
	@ResponseBody
	@RequestMapping(value = "getTaskEm", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getTaskEm(String taskid){
		List<Emtask>emtli = emTaskService.getEmTaskByTakid(taskid);
		JSONArray jsarray = new JSONArray();
		for(Emtask emt : emtli){
			Task t = taskService.getHotelTaskDteail(taskid);
			JSONObject js = new JSONObject();
			js.put("id", emt.getEmid());
			js.put("realname", emt.getRealname());
			js.put("tel", emt.getTel());
			js.put("state", t.getState());
			jsarray.add(js);
		}
		return new ResponseWrapTo(CodeType.success, "", jsarray).toJson();
	}
	
	/**
	 * 
		 * @description	//获取考勤列表
		 * @author  han1088
		 * @param taskid
		 * @param date 格式yyyy-MM-dd
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getTaskAttendance", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getTaskAttendance(String taskid, String date){
		if(date.isEmpty()){
			date = DateUtil.formatYMD(new Date());
		}
		List<Childtask> ctli = childTaskService.getTaskAttendance(taskid, date);
		return new ResponseWrapTo(CodeType.success, "", ctli).toJson();
	}
	
	/**
	 * 
		 * @description	查看已清洁房量按日期统计
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getRoomCountGroupByDate", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getRoomCountGroupByDate(String taskid){
		List<Childtask> roomcountli = childTaskService.getTaskRoomCountGroupByDate(taskid,null);
		JSONArray jsarray = new JSONArray();
		for(Childtask ct : roomcountli){
		    JSONObject js = new JSONObject();
			js.put("date", DateUtil.formatYMD(ct.getCreattime()));
			js.put("roomcount", ct.getRoomcount());
			js.put("result", ct.getResult());
			js.put("roomdetail", ct.getRoomdetail());
			jsarray.add(js);
		}
		return new ResponseWrapTo(CodeType.success, "", jsarray).toJson();
	}
	
	/**
	 * 
		 * @description	确认考勤判断余额是否充足
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "authTaskAttendance", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String authTaskAttendance(String childtaskids){
		Hotelmanager hotelmanager = (Hotelmanager) RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER);
		if(hotelmanager == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		Map<String, Object> data = childTaskService.authTaskAttendance(childtaskids, 
				hotelmanager.getHotelid());
		return new ResponseWrapTo(CodeType.success, "",data).toJson();
	}
	
	/**
	 * 
		 * @description	获取某个帮工考勤
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getTaskEmRoomCount", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getTaskEmRoomCount(String taskid,String emid, String date){
		Map<String, Object> data = childTaskService.getEmTaskAttendance(taskid, emid,date);
		return  new ResponseWrapTo(CodeType.success, "", data).toJson();
	}
	
	/**
	 * 
		 * @description	查看已清洁房量按日期统计
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getRoomCountGroupByEm", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getRoomCountGroupByEm(String taskid){
		List<Childtask> roomcountli = childTaskService.getTaskRoomCountGroupByEm(taskid, null);
		JSONArray jsarray = new JSONArray();
		for(Childtask ct : roomcountli){
			JSONObject js = new JSONObject();
			js.put("realname", ct.getRealname());
			js.put("roomcount", ct.getRoomcount());
			js.put("result", ct.getResult());
			js.put("emid", ct.getEmid().toString());
			js.put("roomdetail", ct.getRoomdetail());
			jsarray.add(js);
		}
		return new ResponseWrapTo(CodeType.success, "", jsarray).toJson();
	}
	
	
	/**
	 * 
		 * @description	帮工接单
		 * @author  han1088
		 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "acceptTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String acceptTask(String taskid, String sessioncode){
		String userid = null;
		Employee employee = (Employee) RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER);
		if(userid == null && employee == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		if(employee != null){
			userid = employee.getUserid().toString();
		}
		Object cachcode = RequestUtil.getSessionAttribute("code");
		boolean isAccept = false;//是否强制报名
		if(sessioncode != null && cachcode != null && sessioncode.equals(cachcode.toString())){
			isAccept = true;
		}
		Map<String , Object> re = emTaskService.acceptTask(userid,taskid, Constant.USER_TYPE_EMPLOYEE,isAccept);
		int code = (int) re.get("code");
		if(code == 0){
			//记录日志
			String host = RequestUtil.getRequest().getRemoteHost();
			Logger logger = new Logger(new Date(), userid, host,employee.getRealname());
			String context = "帮工:"+employee.getRealname()+"，接单";
			TaskLogModel tlm = new TaskLogModel();
			tlm.setContext(context);
			tlm.setOptcode(Constant.logger.LOG_TASK_ADDEM);
			tlm.setTaskid(taskid);
			logManager.creatTaskLog(tlm, logger);
		}
		if(code == -1){//有冲突
			int c = NumberUtil.getRandomNumber(1000, 9999);
			RequestUtil.setSessionAttribute("code", c);
			return new ResponseWrapTo(-2, 
					"服务时间冲突，您在该日期已经报名其他任务，是否继续添加？", c).toJson();
		}
		return new ResponseWrapTo((Integer)re.get("code"), 
				re.get("message").toString(), null).toJson();
	}
	
	/**
	 * 
		 * @description	获取该任务在对应该帮工的排班信息
		 * @author  han1088
		 * @param taskid
		 * @param startTime 开始日期
		 * @param endTime 结束日期
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getEmTaskCalendarDetail", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getEmTaskCalendarDetail(String taskid, String startTime, String endTime){
		Employee employee = null;
		JSONArray jsarray = new JSONArray();
		try{
			employee = (Employee) RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER);
		}catch(Exception e){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		if(employee == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		Task task = taskService.findTaskByTaskid(taskid);
		if(task == null){
			return new ResponseWrapTo(-1, "任务不存在", null).toJson();
		}
		//获取该任务各个日期报名人数
		Map<String, Integer> data = emschedulingService.getEmschedulingCount(taskid, startTime, endTime);
		List<Date> all = DateUtil.getBetweenDates(DateUtil.parseYMD(startTime),DateUtil.parseYMD(endTime));
		for(Date d : all){
			JSONObject js = new JSONObject();
			String dateString = DateUtil.formatYMD(d);//日期
			int surplus = 0;//剩余人数
			int state = 4 ;//状态0可以报名,1有定点任务,2有临时任务，3已经满了,4不在有效期
			
			//搜索日期在任务开始之前全部给剩余0人
			if(task.getStarttime().getTime() > d.getTime()
					|| task.getEndtime().getTime() < d.getTime()){
				state = 4;//不在有效期
			}else{
				int count = data.get(dateString) == null ? 0 : data.get(dateString);//已报名人数
				surplus = task.getUsercount() - count;
				if(surplus == 0){//已经满了
					state = 3;
				}else {
					List<Emscheduling> li = emschedulingService.getEmschedulingByEmidAndDate(employee.getUserid(), dateString);
					if(li == null || li.size() == 0){
						state = 0;//可以报名
					}else{
						Emscheduling ec = li.get(0);
						if(ec.getTasktype().intValue() == 0){
							state = 1;
						}else if(ec.getTasktype().intValue() == 1){
							state = 2;
						}
					}
				}
			}
			js.put("date", dateString);//日期
			js.put("surplus", surplus);//剩余人数
			js.put("state", state);//状态
			jsarray.add(js);
		}
		return new ResponseWrapTo(CodeType.success, "数据获取成功", jsarray).toJson();
	}
	
	/**
	 * 
		 * @description	帮工接单
		 * @author  han1088
		 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "acceptEmTask", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String acceptEmTask(String taskid, String date){
		String userid = null;
		Employee employee = (Employee) RequestUtil.getSessionAttribute(Constant.SESSION_LOGIN_USER);
		if(userid == null && employee == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		if(employee != null){
			userid = employee.getUserid().toString();
		}
		boolean isAccept = false;//是否可以报名
		Task task = taskService.findTaskByTaskid(taskid);
		if(task == null){
			return new ResponseWrapTo(CodeType.fail, 
					"任务不存在", null).toJson();
		}
		String startTime = DateUtil.formatYMD(task.getStarttime());
		String endTime = DateUtil.formatYMD(task.getEndtime());
		if(task.getTasktype() == 0){//定点任务
			Emtask et = emTaskService.getEmFixedTask(employee.getUserid());
			if(et != null && et.getEndtime().getTime() <= task.getStarttime().getTime()){
				return new ResponseWrapTo(CodeType.fail, 
						"已有其他定点任务", null).toJson();
			}
		}
		List<String> dateLi = new ArrayList<String>();//报名的日期
		if(task.getAccepttype() == null || task.getAccepttype().intValue() == 0){//不间断报名
			List<Emscheduling> li = emschedulingService.getEmschedulingByEmId(employee.getUserid(), startTime, endTime);
			if(li != null && li.size() != 0){
				return new ResponseWrapTo(CodeType.fail, 
						"在该任务区间内有其他正在进行的任务", null).toJson();
			}
		}else{
			JSONArray jsonArray = JSONArray.parseArray(date);
			List<String> dateLi2 = new ArrayList<String>();
			for(Object js: jsonArray){
				String datetime = JSONObject.parseObject(js.toString()).getString("date");
				dateLi.add(datetime);
				List<Emscheduling> ecLi = emschedulingService.getEmschedulingByEmidAndDate(employee.getUserid(), datetime);
				if(ecLi != null && ecLi.size() != 0){
					dateLi2.add(datetime);
				}
				int count = emschedulingService.getEmschedulingDateCount(taskid, datetime);
				if((task.getUsercount() - count) == 0){//人数满了
					dateLi2.add(datetime);
				}
			}
			if(dateLi2.size() > 0){
				return new ResponseWrapTo(CodeType.fail, 
						"在该任务区间内有其他正在进行的任务或当日报名人数已满", dateLi).toJson();
			}
		}
		if(task.getAccepttype().intValue() == 0){
			List<Date> li = DateUtil.getBetweenDates(DateUtil.parseYMD(startTime), DateUtil.parseYMD(endTime));
			for(Date d : li){
				dateLi.add(DateUtil.formatYMD(d));
			}
		}
		Map<String , Object> re = emTaskService.acceptTaskNew(userid,taskid, Constant.USER_TYPE_EMPLOYEE);
		int code = (int) re.get("code");
		if(code == 0){
			//记录日志
			String host = RequestUtil.getRequest().getRemoteHost();
			Logger logger = new Logger(new Date(), userid, host,employee.getRealname());
			String context = "帮工:"+employee.getRealname()+"，接单";
			TaskLogModel tlm = new TaskLogModel();
			tlm.setContext(context);
			tlm.setOptcode(Constant.logger.LOG_TASK_ADDEM);
			tlm.setTaskid(taskid);
			logManager.creatTaskLog(tlm, logger);
			//创建排班表
			for(String datetime : dateLi){
				Emscheduling ec = new Emscheduling(employee.getUserid(), taskid, DateUtil.parseYMD(datetime));
				emschedulingService.saveEmscheduling(ec);
			}
		}
		return new ResponseWrapTo((Integer)re.get("code"), 
				re.get("message").toString(), null).toJson();
	}
}
